package com.neusoft.elmboot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

import org.modelmapper.ModelMapper;

import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.po.UserDTO;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.util.*;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ModelMapper modelMapper;

	@Override
	public UserDTO getUserByIdByPass(User user) {
		try {
	        String encryptedInputPassword = AESUtil.encrypt(user.getPassword());
	        user.setPassword(encryptedInputPassword);
	        User reuser = userMapper.getUserByIdByPass(user);
	        if (reuser != null && encryptedInputPassword.equals(reuser.getPassword())) {
	            reuser.setPassword(null); 
	            UserDTO userDTO=modelMapper.map(reuser, UserDTO.class);
	            return userDTO;
	        } else {
	            return null;
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	    }
	}

	@Override
	public User getUserById(String userId) {
		return userMapper.getUserById(userId);
	}

	@Override
	public int saveUser(User user) {
		try {
			if (!user.getUserId().matches("^1[3-9][0-9]{9}$")) { throw new IllegalArgumentException("Invalid phone number format"); }
            String encryptedPassword = AESUtil.encrypt(user.getPassword());
            user.setPassword(encryptedPassword);
         // 生成唯一 API Key
            String apiKey = UUID.randomUUID().toString();
            user.setApiKey(apiKey);
            
            return userMapper.saveUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return 0; 
        }
	}

	@Override
	public int updateUser(User user) {
		return userMapper.updateUser(user);
	}

	@Override
	public int deleteUser(User user) {
		return userMapper.deleteUser(user);
	}

	@Override
	public User getUserByApiKey(String apiKey) {
	    return userMapper.getUserByApiKey(apiKey); // 通过 API Key 查询用户
	}

	@Override
	public int VIPUser(User user) {
		return userMapper.VIPUser(user);
	}

}